package com.qrxl.util;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.qrxl.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
public class ExcelUtil {
    /**
     * @param file       文件对象
     * @param titleRows  标题所占行数
     * @param headerRows header所占行数
     * @param pojoClass  用哪个model来装数据
     * @param <T>
     * @return
     */

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
        if (file == null) {
            throw new CustomException("请选择你要导入的Excel文件");
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        try {
            return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (ExcelImportException e) {
            log.error("导入失败", e);
            throw new CustomException("请传入规范的Excel文件", e);
        } catch (Exception e) {
            log.error("导入失败", e);
            throw new CustomException("导入失败", e);
        }

    }

}
